package com.charon.crawl.kugou.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.context.WebApplicationContext;

import com.charon.common.config.Global;
import com.charon.common.util.ConnectionHandler;
import com.charon.common.util.DateUtils;
import com.charon.common.util.JSUtils;
import com.charon.module.music.dao.SongNewEntityMapper;
import com.charon.module.music.entity.SongListEntity;
import com.charon.module.music.entity.SongListJoinSongEntity;
import com.charon.module.music.entity.SongListRecommendEntity;
import com.charon.module.music.entity.SongNewEntity;
import com.charon.module.music.service.SongListJoinSongService;
import com.charon.module.music.service.SongListRecommendService;
import com.charon.module.music.service.SongListService;
import com.charon.module.music.service.SongNewService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class KGHandler {
	// 配置获取
	private static Global global = new Global("music.properties");
	// 酷狗歌单链接（17800，52000）
	private static String kugouSongList = global.getAttribute("kugou.SongList");
	// 酷狗音乐搜索链接
	private static String kugouSearch = global.getAttribute("kugou.Serach");
	// 酷狗音乐歌手信息页面
	private static String kugouSingerInfo = global.getAttribute("kugou.SingerInfo");
	// 酷狗音乐专辑信息页面
	private static String kugouAlbumInfo = global.getAttribute("kugou.AlbumInfo");
	// 酷狗排行榜Top500页面（23页，每页22条）
	private static String kugouTop500 = global.getAttribute("kugou.Rank.Top500");
	// 酷狗飙升榜（5页）
	private static String kugouImprove = global.getAttribute("kugou.Rank.Improve");
	// 酷狗网络红歌榜（23页）
	private static String kugouNetStar = global.getAttribute("kugou.Rank.NetStar");
	// 酷狗DJ热歌榜（5页）
	private static String kugouDJStar = global.getAttribute("kugou.Rank.DJStar");
	// 酷狗华语新歌榜（5页）
	private static String kugouChineseNew = global.getAttribute("kugou.Rank.ChineseNew");
	// 酷狗欧美新歌榜（5页）
	private static String kugouEurope = global.getAttribute("kugou.Rank.Europe");
	// 酷狗韩国新歌榜（5页）
	private static String kugouKorea = global.getAttribute("kugou.Rank.Korea");
	// 酷狗日本新歌榜（5页）
	private static String kugouJapanese = global.getAttribute("kugou.Rank.Japanese");
	// 酷狗腾讯音乐人原创榜（5页，99条）
	private static String kugouTencent = global.getAttribute("kugou.Rank.Tencent");
	// 酷狗粤语新歌榜（5页）
	private static String kugouCantonese = global.getAttribute("kugou.Rank.Cantonese");
	// 酷狗分享榜（5页）
	private static String kugouShare = global.getAttribute("kugou.Rank.Share");
	// 酷狗美国BillBoard排行榜（5页）
	private static String kugouBillBoard = global.getAttribute("kugou.Rank.BillBoard");
	// 酷狗英国单曲榜（2页，40条）
	private static String kugouEnglish = global.getAttribute("kugou.Rank.English");
	// 酷狗日本公信榜（1页，20条）
	private static String kugouJapanPublic = global.getAttribute("kugou.Rank.JapanPublic");
	// 酷狗韩国M-net音乐榜（3页，50条）
	private static String kugouKoreaM_net = global.getAttribute("kugou.Rank.KoreaM_net");
	// 酷狗中国TOP排行榜（1页，20条）
	private static String kugouChineseTOP = global.getAttribute("kugou.Rank.ChineseTOP");
	// 酷狗歌单排行--飙升
	private static String kugouListImprove = global.getAttribute("kugou.RecommendList.Improve");
	// 酷狗歌单排行--收藏
	private static String kugouListCollect = global.getAttribute("kugou.RecommendList.Collect");
	// 酷狗歌单排行--最热
	private static String kugouListHot = global.getAttribute("kugou.RecommendList.Hot");
	// 酷狗歌单排行--推荐
	private static String kugouListrecommend = global.getAttribute("kugou.RecommendList.Recommend");
	// 酷狗电台全部
	private static String kugouFMAll = global.getAttribute("kugou.FM.all");

	// 歌单列表最小17800，最大520000
	private static String songListURL = "http://www.kugou.com/yy/special/single/";

	private static SongListService sls = null;

	private static SongListRecommendService slrs = null;

	private static SongListJoinSongService sljss = null;
	
	private static SongNewService sns=null;

	/**
	 * @Description: 歌曲排行列表
	 * @Author charon [248135724@qq.com]
	 * @Date: 2018年11月22日 下午2:48:02
	 */
	public static void updateRankLists() {
		HashMap<String, String> map = global.getConfByKeyReg("kugou.RecommendList");
		Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, String> next = iterator.next();
			String type = next.getKey().replace("kugou.RecommendList.", "");
			String url = next.getValue();
			Document doc = ConnectionHandler.getResultDom(url);
			// 每个歌单
			Elements d = doc.getElementById("ulAlbums").getElementsByTag("li");
			int listSize = d.size();
			for (int i = 0; i < listSize; i++) {
				Date date = new Date();
				SongListRecommendEntity sre = new SongListRecommendEntity();
				String listTitle = d.get(i).getElementsByClass("pic").get(0).getElementsByTag("a").get(0).attr("title");
				String listUrl = d.get(i).getElementsByClass("pic").get(0).getElementsByTag("a").get(0).attr("href");
				String listImgUrl1 = d.get(i).getElementsByClass("pic").get(0).getElementsByTag("a").get(0)
						.getElementsByTag("img").get(0).attr("_src");
				// String listImgUrl2 =
				// d.get(i).getElementsByClass("pic").get(0).getElementsByTag("a").get(0)
				// .getElementsByTag("img").get(0).attr("src");
				// String listImgUrlDef =
				// d.get(i).getElementsByClass("pic").get(0).getElementsByTag("a").get(0)
				// .getElementsByTag("img").get(0).attr("_def");
				String listSinger = d.get(i).getElementsByClass("detail").get(0).getElementsByClass("top").get(0)
						.getElementsByTag("em").get(0).text().replace("制作人：", "");
				String listId = listUrl.substring(listUrl.lastIndexOf("/") + 1, listUrl.lastIndexOf("."));
				String songListIntro = d.get(i).getElementsByClass("detail").get(0).getElementsByClass("text").get(0)
						.text();
				sre.setCreateBy("0");
				sre.setListCreateBy(listSinger + "");
				sre.setListImgUrl(listImgUrl1 + "");
				sre.setListUrl(listUrl + "");
				sre.setListId(listId);
				sre.setListType(type);
				sre.setDelFlag("0");
				sre.setListIntro(songListIntro + "");
				sre.setListName(listTitle + "");
				sre.setCreateDate(date);
				sre.setUpdateDate(date);
				sre.setListPlatform("酷狗");
				sre.setListPlatformId(listId);
				slrs.insertSelective(sre);
				updateList(listId);
			}
		}

	}

	/**
	 * @Description: 更新歌曲列表
	 * @Author charon [248135724@qq.com]
	 * @Date: 2018年11月22日 下午2:47:43
	 * @param songListID
	 */
	public static void updateList(String songListID) {
		Date date = new Date();
		SongListEntity sle = new SongListEntity();
		sle.setSongListOriginId(songListID);
		List<SongListEntity> songList = sls.getSongList(sle);
		if (songList == null || songList.size() <= 0
				|| (date.getTime() - songList.get(0).getUpdateDate().getTime()) > 604800000) {

			JSONObject data = JSUtils.getKGSongListData(songListID);
			if (data == null)
				return;
			Date parse = DateUtils.parseDate(data.getString("createDate"));
			JSONObject listInfo = data.getJSONObject("songListInfo");
			JSONArray arr = data.getJSONArray("songList");
			sle.setCreateBy("0");
			sle.setSongListBy(listInfo.getString("specialCreat"));
			sle.setSongListImgUrl(listInfo.getString("specialImg"));
			sle.setSongListExplain(data.getString("songListIntro"));
			sle.setSongListOrigin("酷狗");
			sle.setSongListName(listInfo.getString("specialName") + "");
			sle.setSongListUpdateDate(parse);
			sle.setUpdateDate(date);
			if (songList != null && songList.size() > 0) {
				if (parse.getTime() == songList.get(0).getSongListUpdateDate().getTime())
					return;
				sle.setId(songList.get(0).getId());
				System.out.println("更新");
				sls.updateByPrimaryKey(sle);
			} else {
				System.out.println("插入");
				sle.setCreateDate(date);
				sls.insertSelective(sle);
				SongListJoinSongEntity sljse = new SongListJoinSongEntity();
				sljse.setSongListId(Integer.valueOf(songListID));
				sljss.deleteSelective(sljse);
			}
			StringBuilder sb = new StringBuilder();
			List<SongListJoinSongEntity> listInsert = new ArrayList<SongListJoinSongEntity>();
			for (int x = 0; x < arr.size(); x++) {
				JSONObject obj = arr.getJSONObject(x);
				SongListJoinSongEntity sljse = new SongListJoinSongEntity();
				sljse.setSongListPlatform("酷狗");
				sljse.setSongListPlatformId(songListID);
				sljse.setSongName(obj.getString("songname"));
				sljse.setSongPlatformAlbumId(obj.getString("album_id"));
				sljse.setSongPlatformIdOrHash(obj.getString("hash"));
				sljse.setAlbumName(obj.getString("album_name"));
				sljse.setDelFlag("0");
				sljse.setSingerName(obj.getString("author_name"));
				sljse.setSongTimeLength(obj.getString("timelength"));
				sljse.setCreateBy("0");
				sljse.setUpdateBy("0");
				sljse.setCreateDate(date);
				sljse.setUpdateDate(parse);
				listInsert.add(sljse);
				List<SongListJoinSongEntity> list = sljss.getSongListJoinSong(sljse);
			}
			sljss.deleteBatch(listInsert);
			sljss.insertBatch(listInsert);
		}

		return;
	}

	/**
	 * @Description: 酷狗搜索，返回均为歌曲
	 * @Author charon [248135724@qq.com]
	 * @Date: 2018年11月22日 下午2:47:09
	 * @param keywords
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public static JSONObject kugouSearch(String keywords, Integer page, Integer pageSize) {
		String searchUrl = "http://songsearch.kugou.com/song_search_v2?keyword=" + keywords + "&page=" + page
				+ "&pagesize=" + pageSize
				+ "&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0";
		JSONObject json = ConnectionHandler.getResultJson(searchUrl);
		return json;
	}

	/**
	 * @Description: 获取歌曲信息
	 * @Author charon [248135724@qq.com]
	 * @Date: 2018年11月22日 下午2:46:53
	 * @param hash
	 * @param ablumId
	 * @return
	 */
	public static JSONObject getSongInfo(String hash, String ablumId) {
		String infoUrl = "https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash=" + hash + "&album_id=" + ablumId;
		JSONObject json = ConnectionHandler.getResultJson(infoUrl);
		return json;
	}

	/**
	 * @Description: 获取新歌插入数据库，每日调用一次
	 * @author:charon [248135724@qq.com]
	 * @date:   2018年12月3日 下午11:02:04 
	 * @param:       
	 * @return: void
	 */
	public static void updateNewSongs() {
		String infoUrl = "http://www.kugou.com/";
		Document doc = ConnectionHandler.getResultDom(infoUrl);
		Elements element = doc.getElementById("SongtabContent").getElementsByTag("ul");
		//System.out.println(json.toString());
		//System.out.println(element);
		for(Element ele:element){
			Elements tag = ele.getElementsByTag("li");
			for(Element e:tag){
				JSONObject json = JSONObject.fromObject(e.attr("data"));
				System.out.println(json);
				String hash=json.getString("Hash");
				String fileName=json.getString("FileName");
				String time=json.getString("timeLen");
				String privilege=json.getString("privilege");
				String size=json.getString("size");
				String albumId=json.getString("albumId");
				SongNewEntity sne=new SongNewEntity();
				Date date=new Date();
				String singer=null;
				String songName=null;
				if(fileName.contains("-")){
					singer=fileName.substring(0,fileName.indexOf("-")-1);
					songName=fileName.substring(fileName.indexOf("-")+2,fileName.length());
				}else{
					songName=fileName;
				}
				sne.setSongPlatformIdOrHash(hash);
				sne.setTime(time);
				sne.setAlbumPlatformId(albumId);
				sne.setCreateBy(1+"");
				sne.setFoundDate(date);
				sne.setCreateDate(date);
				sne.setUpdateDate(date);
				sne.setUpdateBy(1+"");
				sne.setNewSongJson(json.toString());
				if("10".equals(privilege)){
					privilege=2+"";
				}else{
					privilege=0+"";
				}
				sne.setPrivilege(privilege);
				sne.setSingerName(singer);
				sne.setSongName(songName);
				sne.setSongLength(size);
				sns.insertSelective(sne);
			}
		}
	}
	
	
	public static void execute(WebApplicationContext wac) {
		// 初始化ServiceBean
		KGHandler.sls = wac.getBean("songListService", SongListService.class);
		KGHandler.slrs = wac.getBean("songListRecommendService", SongListRecommendService.class);
		KGHandler.sljss = wac.getBean("songListJoinSongService", SongListJoinSongService.class);
		KGHandler.sns=wac.getBean("songNewService", SongNewService.class);
		/*
		 * try { KuGouAPI.getSongLists(0,0); } catch (ParseException e) {
		 * e.printStackTrace(); }
		 */
		KGHandler.updateRankLists();

		// System.out.println(KGHandler.sls.getSongList(null));
		// System.out.println(KGHandler.sls.getSongList(null).get(0));
		// System.out.println(KGHandler.slrs.getRecommendList(null));
		// System.out.println(KGHandler.slrs.getRecommendList(null).get(0));
		// System.out.println(KGHandler.sljss.getSongListJoinSong(null));
		// System.out.println(KGHandler.sljss.getSongListJoinSong(null).get(0));
		// KuGouAPI.sljss.getSongListJoinSong(null);
	}

}
